import { useAuthStore } from '@/stores/authStore'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({
  baseURL: 'http://127.0.0.1:3000/api/v1',
})
let authStore = null
instance.interceptors.request.use(
  function (config) {
    console.log(config)
    if (authStore == null) {
      authStore = useAuthStore()
    }
    if (!config.isPublic) {
      config.headers.Authorization = 'Bearer ' + authStore.token
    }
    return config
  },
  function (error) {
    ElMessage.error('程序错误')
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  function (response) {
    let { msg, status, data } = response.data
    if (status >= 400) {
      ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    } else {
      if (status != 200) {
        ElMessage.error(msg)
      }
      return data
    }
  },
  function (error) {
    ElMessage.error('程序错误')
    return Promise.reject(error)
  },
)
export default instance
